<?php
namespace app\shop\controller;
use think\Db;
use lib\NativePay;
use wxpaypc\WxPayUnifiedOrder;
use lib\UserCrypt;
class Order extends Base{
    public function submit_order(){
        if(request()->isGet()){
            $address=Db::name('address')->where('user_id',session('userinfo')['id'])->where('state',1)->find();
            if($address){
                $params=input("param.");
                $cates=Db::name('cates')->where('f_id',0)->where('state',1)->select();
                if($params['type']==1){
                    $productDetail=Db::name('product')->where('id',$params['p_id'])->find();
                    if($productDetail){
                        $spec_combination=Db::name('spec_combination')->where('id',$params['spec_combination_id'])->where('state',1)->find();
                        $productDetail['price']=$spec_combination['money'];
                        $productDetail['num']=$spec_combination['num'];
                        $productDetail['combination']=$spec_combination['combination'];
                    }
                }
                $this->assign('productDetail',$productDetail);
                $this->assign('cates',$cates);
                $this->assign('address',$address);
                $this->assign('buy_num',$params['buy_num']);
                $this->assign('spec_combination_id',$params['spec_combination_id']);
                $this->assign('url',$this->request->domain());
                $this->assign('system',$this->system_set());
                return $this->fetch();
            }else{
                $this->redirect(url('my/my#address'));
            }
        }elseif(request()->isPost()){

        }
        
    }
    public function submit_order_spot(){
        if(request()->isGet()){
            $address=Db::name('address')->where('user_id',session('userinfo')['id'])->where('state',1)->find();
            if($address){
                $params=input("param.");
                $cates=Db::name('cates')->where('f_id',0)->where('state',1)->select();
                if($params['type']==2){
                    $productDetail=Db::name('scenic_spot')->where('id',$params['p_id'])->find();
                }
                $this->assign('productDetail',$productDetail);
                $this->assign('cates',$cates);
                $this->assign('address',$address);
                $this->assign('buy_num',$params['buy_num']);
                $this->assign('url',$this->request->domain());
                $this->assign('system',$this->system_set());
                return $this->fetch();
            }else{
                $this->redirect(url('my/my#address'));
            }
        }elseif(request()->isPost()){

        }
        
    }
    public function submit_orders(){
        if(request()->isGet()){
            $address=Db::name('address')->where('user_id',session('userinfo')['id'])->where('state',1)->find();
            if($address){
                $params=input("param.");
                $cates=Db::name('cates')->where('f_id',0)->where('state',1)->select();
                $car_ids=json_decode(input("param.carts"));
                $nums=0;
                $moneys=0;
                foreach ($car_ids as $key => $value) {
                    $nums=$nums+$car_ids[$key]->buy_num;
                    $moneys=$moneys+bcmul($car_ids[$key]->title_img->price,$car_ids[$key]->buy_num,2);
                    if($car_ids[$key]->type==1){
                        // $carts[$key]=Db::name('product')->where('id',$car_ids[$key]->p_id)->find();
                        $carts[$key]['id']=$car_ids[$key]->id;
                        $carts[$key]['p_id']=$car_ids[$key]->p_id;
                        $carts[$key]['price']=$car_ids[$key]->title_img->price;
                        $carts[$key]['img']=$car_ids[$key]->title_img->img;
                        $carts[$key]['buy_num']=$car_ids[$key]->buy_num;
                        $carts[$key]['title']=$car_ids[$key]->title_img->title;
                        $carts[$key]['type']=$car_ids[$key]->type;
                        $carts[$key]['combination']=$car_ids[$key]->title_img->combination;
                        $carts[$key]['spec_combination_id']=$car_ids[$key]->spec_combination_id;
                    }elseif($car_ids[$key]->type==2){
                        // $carts[$key]=Db::name('scenic_spot')->where('id',$car_ids[$key]->p_id)->find();
                        $carts[$key]['id']=$car_ids[$key]->id;
                        $carts[$key]['p_id']=$car_ids[$key]->p_id;
                        $carts[$key]['price']=$car_ids[$key]->title_img->price;
                        $carts[$key]['buy_num']=$car_ids[$key]->buy_num;
                        $carts[$key]['img']=$car_ids[$key]->title_img->img;
                        $carts[$key]['title']=$car_ids[$key]->title_img->title;
                        $carts[$key]['type']=$car_ids[$key]->type;
                        $carts[$key]['combination']=$car_ids[$key]->title_img->combination;
                        $carts[$key]['spec_combination_id']=$car_ids[$key]->spec_combination_id;
                    }
                    
                }
                
                $this->assign('carts',$carts);
                $this->assign('cartstr',json_encode($carts));
                $this->assign('cates',$cates);
                $this->assign('address',$address);
                $this->assign('nums',$nums);
                $this->assign('moneys',$moneys);
                $this->assign('url',$this->request->domain());
                $this->assign('system',$this->system_set());
                return $this->fetch();
            }else{
                $this->redirect(url('my/my#address'));
            }
        }elseif(request()->isPost()){

        }
        
    }
    // 门票下单
    public function spotOrderin()
    {
        $data['p_id']=input("param.p_id");
        $data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
        $data['pay_fees']=input("param.pay_fees");
        
        $token=input("param.token");
        $data['buy_num']=input("param.buy_num");
        $data['price']=input("param.price");
        if ($data['pay_fees']!=bcmul(input("param.buy_num"),input("param.price"),2)) {
            return json(['code' => 500, 'msg' => '数量与单价与支付金额不匹配，请刷新页面重试']);
        }
        $data['deduct_moneys']=input("param.deduct_moneys");
        $data['spec_combination_id']=0;
        $data['name']=input("param.name");
        $data['phone']=input("param.phone");
        $data['address']=input("param.address");
        $data['address_id']=input("param.address_id");
        
        if(!empty(input("param.message"))){
            $data['message']=input("param.message");
        }
        $uid=UserCrypt::do_mdecrypt($token);

        $data['user_id']=$uid;
        $data['pay_style']=2;
        if ($data['price']==0&&$data['pay_fees']==0) {
            $data['state']=2;
        }else{
            $data['state']=1;
        }
        $data['is_cart']=1;
        $data['sub']=1;
        $data['order_type']=2;
        $data['time']=time();
        $data['uptime']=time();


        Db::startTrans();
        try {
            $orderId=Db::name('orders')->insertGetId($data);
            $datasub['user_id']=$uid;
            $datasub['orders_id']=$orderId;
            $datasub['title']=input("param.title");
            $datasub['ordernosub']=$data['orderno'].'1';
            $datasub['cart_id']=0;
            $datasub['p_id']=$data['p_id'];
            $datasub['buy_num']=$data['buy_num'];
            $datasub['deduct_money']=$data['deduct_moneys'];
            $datasub['pay_fee']=$data['pay_fees'];
            $datasub['price']=$data['price'];
            $datasub['spec_combination_id']=$data['spec_combination_id'];
            $datasub['order_type']=2;
            $datasub['state']=$data['state'];
            $datasub['time']=time();
            $datasub['uptime']=time();
            $ordersubId=Db::name('ordersub')->insertGetId($datasub);
            
            //佣金抵扣
            if ($data['deduct_moneys']>0) {
                Db::name('users')->where('id', $uid)->setDec('money',$data['deduct_moneys']);
                $datascore2['user_id']=$uid;
                $datascore2['orders_id']=$ordersubId;
                $datascore2['money']=$data['deduct_moneys'];
                $datascore2['type']=2;
                $datascore2['time']=time();
                $datascore2['uptime']=time();
                Db::name('money_bill')->insertGetId($datascore2);
            }
            // 提交事务
            Db::commit();
            $notify = new NativePay();
            $input = new WxPayUnifiedOrder();

            $input->setBody(input("param.title"));
            $input->setAttach(input("param.title"));
            $input->SetOut_trade_no($data['orderno']);
            $input->SetTotal_fee(floatval($data['pay_fees'] * 100));//以分为单位
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag('门票');

            $input->SetNotify_url($this->request->domain()."/api/orders/notify");
            $input->SetTrade_type("NATIVE");
            //$product_id 为商品自定义id 可用作订单ID
            $input->SetProduct_id($data['p_id']);
            $result = $notify->getPayUrl($input);
            if (empty($result['code_url'])){
                $qrCode_url = '';
            }else{
                $qrCode_url = $result["code_url"];
            }
            

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        $return['qrcode_url']=$qrCode_url;
        $return['pay_fees']=input("param.pay_fees");
        $return['title']=input("param.title");
        $return['orderno']=$data['orderno'];
        return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
    }
    public function orderin(){
        $data['p_id']=input("param.p_id");
        $data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
        $data['pay_fees']=input("param.pay_fees");
        $data['combination']=input("param.combination");
        
        $token=input("param.token");
        $data['buy_num']=input("param.buy_num");
        $data['price']=input("param.price");
        if ($data['pay_fees']!=bcmul(input("param.buy_num"),input("param.price"),2)) {
            return json(['code' => 500, 'msg' => '数量与单价与支付金额不匹配，请刷新页面重试']);
        }
        $data['deduct_moneys']=input("param.deduct_moneys");
        $data['spec_combination_id']=input("param.spec_combination_id");
        $data['name']=input("param.name");
        $data['phone']=input("param.phone");
        $data['address']=input("param.address");
        $data['address_id']=input("param.address_id");
        
        if(!empty(input("param.message"))){
            $data['message']=input("param.message");
        }
        $uid=UserCrypt::do_mdecrypt($token);

        $data['user_id']=$uid;
        $data['pay_style']=2;

        $data['state']=1;
        $data['is_cart']=1;
        $data['sub']=1;
        $data['order_type']=1;
        $data['time']=time();
        $data['uptime']=time();


        Db::startTrans();
        try {
            $orderId=Db::name('orders')->insertGetId($data);
            $datasub['user_id']=$uid;
            $datasub['orders_id']=$orderId;
            $datasub['title']=input("param.title");
            $datasub['ordernosub']=$data['orderno'].'1';
            $datasub['cart_id']=0;
            $datasub['p_id']=$data['p_id'];
            $datasub['buy_num']=$data['buy_num'];
            $datasub['deduct_money']=$data['deduct_moneys'];
            $datasub['pay_fee']=$data['pay_fees'];
            $datasub['price']=$data['price'];
            $datasub['spec_combination_id']=$data['spec_combination_id'];
            $datasub['combination']=$data['combination'];
            $datasub['order_type']=1;
            $datasub['state']=1;
            $datasub['time']=time();
            $datasub['uptime']=time();
            $ordersubId=Db::name('ordersub')->insertGetId($datasub);
            Db::name('spec_combination')->where('id',$data['spec_combination_id'])->setDec('num',$data['buy_num']);//减库存
            
            //佣金抵扣
            if ($data['deduct_moneys']>0) {
                Db::name('users')->where('id', $uid)->setDec('money',$data['deduct_moneys']);
                $datascore2['user_id']=$uid;
                $datascore2['orders_id']=$ordersubId;
                $datascore2['money']=$data['deduct_moneys'];
                $datascore2['type']=2;
                $datascore2['time']=time();
                $datascore2['uptime']=time();
                Db::name('money_bill')->insertGetId($datascore2);
            }
            // 提交事务
            Db::commit();
            $notify = new NativePay();
            $input = new WxPayUnifiedOrder();

            $input->setBody(input("param.title"));
            $input->setAttach(input("param.title"));
            $input->SetOut_trade_no($data['orderno']);
            $input->SetTotal_fee(floatval($data['pay_fees'] * 100));//以分为单位
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag($data['combination']);

            $input->SetNotify_url($this->request->domain()."/api/orders/notify");
            $input->SetTrade_type("NATIVE");
            //$product_id 为商品自定义id 可用作订单ID
            $input->SetProduct_id($data['p_id']);
            $result = $notify->getPayUrl($input);
            if (empty($result['code_url'])){
                $qrCode_url = '';
            }else{
                $qrCode_url = $result["code_url"];
            }
            

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        $return['qrcode_url']=$qrCode_url;
        $return['pay_fees']=input("param.pay_fees");
        $return['title']=input("param.title");
        $return['orderno']=$data['orderno'];
        return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
    }
    public function corderIn()
    {
        $token=input("param.token");
        $cartstr=input("param.carts_arr");
        $car_ids=json_decode(htmlspecialchars_decode($cartstr));
        $data['deduct_moneys']=0;
        $data['pay_fees']=input("param.pay_fees");
        
        $data['name']=input("param.name");
        $data['phone']=input("param.phone");
        $data['address']=input("param.address");
        $data['address_id']=input("param.address_id");
        
        if(!empty(input("param.message"))){
            $data['message']=input("param.message");
        }

        $uid=UserCrypt::do_mdecrypt($token);
        $data['user_id']=$uid;
        if ($car_ids[0]->type==1) {
            $body=Db::name('product')->where('id',$car_ids[0]->p_id)->value('title');
        }elseif($car_ids[0]->type==2) {
            $body=Db::name('scenic_spot')->where('id',$car_ids[0]->p_id)->value('title');
        }
        $data['p_id']=$car_ids[0]->p_id;
        $data['pay_style']=2;
        $data['buy_num']=$car_ids[0]->buy_num;
        $data['price']=$car_ids[0]->price;
        $data['spec_combination_id']=$car_ids[0]->spec_combination_id;
        $data['combination']=$car_ids[0]->combination;
        $data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
        $data['state']=1;
        $data['is_cart']=2;
        $data['order_type']=3;
        if(count($car_ids)>1){
            $data['sub']=2;
        }elseif(count($car_ids)==1){
            $data['sub']=1;
        }
        $data['time']=time();
        $data['uptime']=time();

        Db::startTrans();
        try {
            $orderId=Db::name('orders')->insertGetId($data);

            foreach ($car_ids as $key => $value) {
                $datasub['user_id']=$uid;
                $datasub['orders_id']=$orderId;
                if ($car_ids[$key]->type==1) {
                    $datasub['title']=Db::name('product')->where('id',$car_ids[$key]->p_id)->value('title');
                }elseif($car_ids[$key]->type==2) {
                    $datasub['title']=Db::name('scenic_spot')->where('id',$car_ids[$key]->p_id)->value('title');
                }
                $datasub['ordernosub']=$data['orderno'].$key;
                $datasub['cart_id']=$car_ids[$key]->id;
                $datasub['p_id']=$car_ids[$key]->p_id;
                $datasub['buy_num']=$car_ids[$key]->buy_num;
                $datasub['price']=$car_ids[$key]->price;
                $datasub['spec_combination_id']=$car_ids[$key]->spec_combination_id;
                $datasub['combination']=$car_ids[$key]->combination;
                $datasub['deduct_money']=0;
                $datasub['pay_fee']=bcmul($datasub['buy_num'],$datasub['price'],2);
                if($car_ids[$key]->type==1){
                    $datasub['order_type']=1;
                    Db::name('spec_combination')->where('id',$car_ids[$key]->spec_combination_id)->setDec('num',$car_ids[$key]->buy_num);//减库存
                }elseif($car_ids[$key]->type==2){
                    $datasub['order_type']=2;
                }
                $datasub['state']=1;
                $datasub['time']=time();
                $datasub['uptime']=time();
                Db::name('ordersub')->insert($datasub);
                Db::name('carts')->where('id',$car_ids[$key]->id)->update(['state'=>3,'uptime'=>time()]);
            }

            //购物车下单不支持佣金抵扣(分订单里不好分配,平方会出现有的支付金额为负;按比例分闲麻烦)

            // 提交事务
            Db::commit();
            $notify = new NativePay();
            $input = new WxPayUnifiedOrder();

            $input->setBody($body.'...');
            $input->setAttach($body.'...');
            $input->SetOut_trade_no($data['orderno']);
            $input->SetTotal_fee(floatval($data['pay_fees'] * 100));//以分为单位
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag($data['combination'].'...');

            $input->SetNotify_url($this->request->domain()."/api/orders/notify");
            $input->SetTrade_type("NATIVE");
            //$product_id 为商品自定义id 可用作订单ID
            $input->SetProduct_id($data['p_id']);
            $result = $notify->getPayUrl($input);
            if (empty($result['code_url'])){
                $qrCode_url = '';
            }else{
                $qrCode_url = $result["code_url"];
            }
            $return['qrcode_url']=$qrCode_url;
            $return['pay_fees']=input("param.pay_fees");
            $return['title']=$body.'...';
            $return['orderno']=$data['orderno'];
            return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '事物回滚失败！']);
        }
    }
    public function payment()
    {
        $cates=Db::name('cates')->where('f_id',0)->where('state',1)->select();
        $this->assign('qrcode',input("param.qrcode_url"));
        $this->assign('cates',$cates);
        $this->assign('title',input("param.title"));
        $this->assign('orderno',input("param.orderno"));
        $this->assign('pay_fees',input("param.pay_fees"));
        $this->assign('url',$this->request->domain());
        $this->assign('system',$this->system_set());
        return $this->fetch();
    }
    public function is_pay_success()
    {
        $orderno=input("param.orderno");
        $orders_state=Db::name('orders')->where('orderno',$orderno)->value('state');
        $ordersub_state=Db::name('ordersub')->where('ordernosub',$orderno)->value('state');
        if ($orders_state==2||$ordersub_state==2) {
            return json(['code' => 200, 'msg' => '成功！']);
        }else{
            return json(['code' => 500, 'msg' => '失败！']);
        }
    }

    public function order_detail(){
        $id=input("param.id");
        $cates=Db::name('cates')->where('f_id',0)->where('state',1)->select();
        $res=Db::name('ordersub')->alias('a')->join('orders b', 'a.orders_id = b.id','LEFT')->where('a.id',$id)->field('a.*,b.name,b.phone,b.address,b.message')->find();
        if($res){
            if($res['order_type']==1){
                $res['img']=Db::name('product')->where('id',$res['p_id'])->value('img');
            }elseif($res['order_type']==2){
                $res['img']=Db::name('scenic_spot')->where('id',$res['p_id'])->value('img');
            }
            $res['time']=date('Y-m-d H:i:s',$res['time']);
            if($res['fktime']>0){
                $res['fktime']=date('Y-m-d H:i:s',$res['fktime']);
            }else{
                $res['fktime']='';
            }
            if($res['fhtime']>0){
                $res['fhtime']=date('Y-m-d H:i:s',$res['fhtime']);
            }else{
                $res['fhtime']='';
            }
        }
        $this->assign('cates',$cates);
        $this->assign('res',$res);
        $this->assign('url',$this->request->domain());
        $this->assign('system',$this->system_set());
        return $this->fetch();
    }
}
